<!DOCTYPE html>
<html lang='en'>

<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <meta http-equiv='X-UA-Compatible' content='ie=edge'>
  <title>Document</title>
</head>

<body>
  <input type="text" id="words">
  <input type="button" value="发布" id="btn">

  <script>
    const btn = document.querySelector('#btn');
    const words = document.querySelector('#words');

    btn.addEventListener('click', () => btnClick());

    document.addEventListener('keydown', e => {
      if (e.keyCode === 13) btnClick();
    });

    function btnClick() {
      let timer = null;
      let barrage = words.value;
      words.value = '';
      let span = document.createElement('span');
      span.innerHTML = barrage;
      span.style.position = 'absolute';
      span.style.left = '1200px';
      // 对浏览器可视窗口高度取随机数，让每个span的高度不一样
      span.style.top = Math.floor(Math.random() * document.documentElement.clientHeight) + 'px';
      let randomColor = `rgb(${getRandom(0, 255)},${getRandom(0, 255)},${getRandom(0, 255)})`;
      span.style.color = randomColor;
      document.body.appendChild(span);
      timer = setInterval(() => {
        span.style.left = parseInt(span.style.left) - 5 + 'px';
        // 当left值小于-span内容的宽度时会在页面中消失，移除该元素
        if (parseInt(span.style.left) < -span.offsetWidth) {
          clearInterval(timer);
          document.body.removeChild(span);
        }
      }, 15);
    }

    // 得到两个数之间的随机整数（包括这两个数）
    function getRandom(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
  </script>
</body>

</html>